package com.alibaba.citrus.cr.platform.enhance.facade.service.log;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.annotation.Resource;

import com.alibaba.citrus.cr.common.annotation.FacadeInvoker;
import com.alibaba.citrus.cr.platform.enhance.repository.OperateLogWriteRepository;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.cz.base.tool.log.model.OpLogModel;
import com.alibaba.lattice2.epoch.sdk.model.Result;

import com.epoch.app.crplatformenhance.model.dto.OperateWriteInfoRequest;
import com.epoch.app.crplatformenhance.writeoperatelog.service.WriteOperateLogService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;

/**
 * @author: qiaojiange
 * @create: 2021/11/09
 * @Description 写入操作日志实现类
 */
@Component
public class WriteOperateLogServiceImpl implements WriteOperateLogService {
    private static Log log = Log.getLogger(WriteOperateLogServiceImpl.class);

    @Resource
    private OperateLogWriteRepository writeRepository;

    @Override
    @FacadeInvoker(errorCode = "OTS-12-002-01-10-002")
    public Result<Boolean> writeOperateLog(OperateWriteInfoRequest operateWriteInfoRequest) {
        if (operateWriteInfoRequest == null) {
            return Result.fail("", "参数不能为空！");
        }
        com.epoch.app.crplatformenhance.domain.operatelog.model.OperateLog operateLog = new com.epoch.app.crplatformenhance.domain.operatelog.model.OperateLog();
        BeanUtils.copyProperties(operateWriteInfoRequest,operateLog);
        Boolean result = writeRepository.write(operateLog);
        return result ? Result.success(result) : Result.fail("OTS-12-002-01-10-002", "该操作日志写入失败！");
    }

    /**
     * 写入操作日志
     *
     * @param request
     * @return
     * @throws ParseException
     */
    /**
     * todo qjg 测试代码
     * @param request
     * @return
     * @throws ParseException
     */
    @Override
    public Result<Void> testWrite(OperateWriteInfoRequest request)   {
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        Date oldDate = null;
        try {
            oldDate = format.parse("1970-00-11 12:22:13");
        } catch (ParseException e) {
            e.printStackTrace();
        }

        OpLogModel<Date> opLogModel = OpLogModel.<Date>builder().operatorType(request.getOperatorType())
                .oldValue(oldDate).newValue(new Date()).objectId(request.getObjectId()).dataType(request.getDataType())
                .remark(request.getRemark()).traceId("traceid---").build();
        log.asyncMonitorObjectChangeV2(opLogModel);
        log.error("-----测试写入完成----");
        return Result.success(null);
    }
}
